#!/usr/bin/perl

use strict;

use Switch;
use Time::HiRes;

use API::Document;
use API::Query;
use API::Retrieval;
use API::Index;

print "Enter your query or type q to quit\n>";
my $queryinput= <STDIN>;
my $istart = [ Time::HiRes::gettimeofday( ) ];
my $elapsed = Time::HiRes::tv_interval( $istart );

while ($queryinput ne "q\n"){
  # a dash indicates the input is a "request"
  if (substr($queryinput, 0, 1) eq "-") { 
    my ($firstword, $request) = split(/\s+/, $queryinput, 2);
    $istart = [ Time::HiRes::gettimeofday( ) ];
    switch ($firstword) {
      case "-df" { Retrieval::find_docs($request); }
      case "-freq" { Retrieval::find_freq($request); }
      case "-doc" { Index::find_fulltext($request); }
      case "-tf" { Document::find_tf($request); }
      case "-title" { Index::find_title($request); }
      case "-similar" { Retrieval::find_similar_context($request); }
      else { print "Wrong request, please try again\n"; }
    }
    $elapsed = Time::HiRes::tv_interval( $istart );
    print "\n-------------------- Processing time: $elapsed seconds --------------------\n\n";
  } else {
  # no dash means this is a query
    print "query input: $queryinput\n";
    do_query($queryinput);
  }

  # take another user input query
  print "Enter your query or type q to quit\n>";
  $queryinput=<STDIN>;
  print "\n";
}

sub do_query {
  my $queryinput = shift;
  my @searchTerms = Query::preprocess $queryinput;  

  my $istart = [ Time::HiRes::gettimeofday( ) ];
  # search for the term
  my ($score_ref, $loc_ref) = Retrieval::execute_query @searchTerms;

  my %results = %$score_ref;
  my %locations = %$loc_ref;
  my @sortedResults = reverse sort {$results{$a} <=> $results{$b}} keys %results;
  my $elapsed = Time::HiRes::tv_interval( $istart );
  # display the resutl
  foreach my $result(@sortedResults){
    my $snippet =  Document::summary($result, $locations{$result});
    print "DocID: $result  \tScore: $results{$result}\t$snippet\n"; 
  }

  print "\n-------------------- Processing time: $elapsed seconds --------------------\n\n";
}

